package com.ErpCoreWeb.Security.Org;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CBaseObjectMgr;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.ColumnType;
import com.ErpCoreModel.Framework.DatabaseType;
import com.ErpCoreModel.Framework.DbParameter;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreWeb.Common.Global;
import com.mongodb.BasicDBObject;

/**
 * Servlet implementation class OrgPanel
 */
@WebServlet("/OrgPanel")
public class OrgPanel extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    public CTable m_Table = null;
    public CCompany m_Company = null;  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgPanel() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }
        String B_Company_id = request.getParameter("B_Company_id");
		if (Global.IsNullParameter(B_Company_id))
			m_Company = Global.GetCtx(this.getServletContext())
					.getCompanyMgr().FindTopCompany();
		else
			m_Company = (CCompany) Global.GetCtx(this.getServletContext())
					.getCompanyMgr().Find(Util.GetUUID(B_Company_id));

        m_Table = (CTable)m_Company.getOrgMgr().getTable();
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Delete"))
        {
        	Delete();
            return ;
        }
	}
    void GetData()
    {
    	int page = Integer.valueOf(request.getParameter("page"));
		int pageSize = Integer.valueOf(request.getParameter("pagesize"));

        String sData = "";
        List<CBaseObject> lstObj = m_Company.getOrgMgr().GetList();
        
        int totalPage = lstObj.size() % pageSize == 0 ? lstObj.size() / pageSize : lstObj.size() / pageSize + 1; // 计算总页数

        int index = (page - 1) * pageSize; // 开始记录数  
        for (int i = index; i < pageSize + index && i < lstObj.size(); i++)
        {
            CBaseObject obj = (CBaseObject)lstObj.get(i);

            String sRow="";
            for (CBaseObject objC : m_Table.getColumnMgr().GetList())
            {
                CColumn col = (CColumn)objC;
                if (col.getColType() == ColumnType.object_type)
                {
                    String sVal = "";
                    if (obj.GetColValue(col) != null)
                        sVal = "long byte";
                    sRow += String.format("\"%s\":\"%s\",", col.getCode(), sVal);
                }
                else if (col.getColType() == ColumnType.ref_type)
                {
                    CTable RefTable = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(col.getRefTable());
                    if (RefTable == null) continue;
                    CBaseObjectMgr objRefMgr = new CBaseObjectMgr();
                    objRefMgr.TbCode = RefTable.getCode();
                    objRefMgr.Ctx = Global.GetCtx(this.getServletContext());

                    CColumn RefCol = (CColumn)RefTable.getColumnMgr().Find(col.getRefCol());
                    CColumn RefShowCol = (CColumn)RefTable.getColumnMgr().Find(col.getRefShowCol());

                    String sVal = "";
                    if (objRefMgr.Ctx.getMainDB().m_DbType == DatabaseType.MongoDb)
                    {
                    	BasicDBObject query = new BasicDBObject();  
                        query.put(RefCol.getBsonCode(), obj.GetColValue(col));
                        List<CBaseObject> lstObj2 = objRefMgr.GetList(query, null, 0, 0);
                        if (lstObj2.size() > 0)
                        {
                            CBaseObject obj2 = lstObj2.get(0);
                            Object objVal2 = obj2.GetColValue(RefShowCol);
                            if (objVal2 != null)
                                sVal = objVal2.toString();
                        }
                    }
                    else
                    {
	                    String sWhere = String.format(" %s=%s", RefCol.getCode(),obj.GetColSqlValue(col));
	                    List<CBaseObject> lstObj2 = objRefMgr.GetList(sWhere);
	                    if (lstObj2.size() > 0)
	                    {
	                        CBaseObject obj2 = lstObj2.get(0);
	                        Object objVal = obj2.GetColValue(RefShowCol);
	                        if (objVal != null)
	                            sVal = objVal.toString();
	                    }
                    }
                    sRow += String.format("\"%s\":\"%s\",", col.getCode(), sVal);
                }
                else
                {
                    String sVal = "";
                    Object objVal = obj.GetColValue(col);
                    if (objVal != null)
                        sVal = objVal.toString();
                    StringBuffer temp=new StringBuffer();
                    temp.append(sVal);
                    com.ErpCoreWeb.Common.Util.ConvertJsonSymbol(temp);
                    sVal=temp.toString();
                    sRow += String.format("\"%s\":\"%s\",", col.getCode(), sVal);
                }

            }
			if (sRow.endsWith(","))
				sRow = sRow.substring(0, sRow.length() - 1);
            sRow = "{" + sRow + "},";
            sData += sRow;
        }
		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, lstObj.size());

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void Delete()
    {
        String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
        	try {
				response.getWriter().print("请选择记录！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        m_Company.getOrgMgr().Delete(Util.GetUUID(delid));
        if (!m_Company.getOrgMgr().Save(true))
        {
        	try {
				response.getWriter().print("删除失败！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
    }
}
